package dao;

import common.Course;
import util.SnowflakeIdGenerator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class NewClass {
    private static Connection conn=DataBaseConnect.getConn();
    private static String sql="INSERT INTO course (name,teacherId,teacherName,description,code) VALUES(?,?,?,?,?)";
    private static PreparedStatement pstmt;
    static {
        try {
            pstmt=conn.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static boolean newClass(Course course){
        //考虑到雪花算法的极端情况，如果生成的邀请码重复了
        //尝试添加3次，如果邀请码不重复，添加成功就return，否则重新生成邀请码
        //如果几次都重复了，那就有问题了。
        for(int i=1;i<=5;i++){
            try {
                pstmt.setString(1,course.getName());
                pstmt.setString(2,course.getTeacherId());
                pstmt.setString(3,course.getTeacherName());
                pstmt.setString(4, course.getDescription());
                pstmt.setString(5, SnowflakeIdGenerator.ID(8));
                int count=pstmt.executeUpdate();
                if(count==1){
                    System.out.println("新建课程成功");
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("新建课程失败");
            }
        }
         return false;
    }
}
